<?php

namespace App\Http\Controllers;

use App\Models\MembershipCode;
use App\Models\MembershipProduct;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Exception;

class MembershipController extends Controller
{
    /**
     * 显示会员中心页面
     */
    public function index()
    {
        $user = Auth::user();
        
        return view('membership.index', [
            'user' => $user,
            'isMember' => $user->isMember(),
            'membershipType' => $user->getMembershipTypeName(),
            'daysLeft' => $user->getMembershipDaysLeft(),
        ]);
    }
    
    /**
     * 显示会员权益页面
     */
    public function benefits()
    {
        $user = Auth::user();
        $products = MembershipProduct::getActiveProducts();
        
        return view('membership.benefits', [
            'user' => $user,
            'isMember' => $user->isMember(),
            'membershipType' => $user->getMembershipTypeName(),
            'daysLeft' => $user->getMembershipDaysLeft(),
            'products' => $products,
        ]);
    }
    
    /**
     * 显示兑换页面
     */
    public function redeemForm()
    {
        return view('membership.redeem');
    }
    
    /**
     * 兑换会员
     */
    public function redeem(Request $request)
    {
        $request->validate([
            'code' => 'required|string|min:8|max:20',
        ]);
        
        $user = Auth::user();
        $code = $request->input('code');
        
        try {
            DB::beginTransaction();
            
            $membershipCode = MembershipCode::where('code', $code)
                ->where('is_used', false)
                ->whereNull('used_by')
                ->first();

            if (!$membershipCode) {
                throw new Exception('兑换码不存在');
            }

            if (!$membershipCode->isValid()) {
                throw new Exception('兑换码无效或已过期');
            }

            // 兑换会员
            $newExpiry = $membershipCode->redeem($user);
            
            DB::commit();
            
            return response()->json([
                'success' => true,
                'message' => '兑换成功',
                'data' => [
                    'membership_type' => $user->getMembershipTypeName(),
                    'expires_at' => $newExpiry ? $newExpiry->format('Y-m-d H:i:s') : null,
                    'days_left' => $user->getMembershipDaysLeft(),
                ]
            ]);
            
        } catch (Exception $e) {
            DB::rollBack();
            
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }
    
    /**
     * 获取会员状态
     */
    public function status()
    {
        $user = Auth::user();

        
        return response()->json([
            'is_member' => $user->isMember(),
            'membership_type' => $user->getMembershipTypeName(),
            'expires_at' => $user->membership_expires_at ? $user->membership_expires_at->format('Y-m-d H:i:s') : null,
            'days_left' => $user->getMembershipDaysLeft(),
        ]);
    }

    /**
     * 会员历史记录页面
     */
    public function history()
    {
        return view('membership.history');
    }
    
    /**
     * 获取会员历史记录数据（分页）
     */
    public function getHistoryData(Request $request)
    {
        $user = Auth::user();
        $filter = $request->input('filter', 'all');
        $page = $request->input('page', 1);
        $perPage = $request->input('per_page', 10);
        
        $query = $user->membershipCodes()->orderBy('used_at', 'desc');
        
        // 根据筛选条件过滤
        if ($filter === 'success') {
            $query->where('is_used', true);
        } elseif ($filter === 'failed') {
            $query->where('is_used', false);
        }
        
        $total = $query->count();
        $codes = $query->skip(($page - 1) * $perPage)
                      ->take($perPage)
                      ->get()
                      ->map(function ($code) {
                          return [
                              'id' => $code->id,
                              'code' => $code->code,
                              'memberType' => $code->getTypeName(),
                              'redeemDate' => $code->used_at ? $code->used_at->format('Y-m-d H:i:s') : null,
                              'startDate' => $code->effective_start_at ? $code->effective_start_at->format('Y-m-d H:i:s') : null,
                              'endDate' => $code->effective_end_at ? $code->effective_end_at->format('Y-m-d H:i:s') : null,
                              'status' => $code->getStatusName()
                          ];
                      });
        
        // 统计信息
        $stats = [
            'total' => $user->membershipCodes()->count(),
            'success' => $user->membershipCodes()->where('is_used', true)->count(),
            'failed' => $user->membershipCodes()->where('is_used', false)->count()
        ];
        
        return response()->json([
            'data' => $codes,
            'meta' => [
                'current_page' => $page,
                'per_page' => $perPage,
                'total' => $total,
                'last_page' => ceil($total / $perPage)
            ],
            'stats' => $stats
        ]);
    }
}